import fs from "node:fs/promises";
import path from "node:path";
import { RunnerSpec } from "./types";

export const WORKFLOW_ROOT = path.resolve(__dirname, "..", "..");
export const LOGS_ROOT = path.join(WORKFLOW_ROOT, "logs");

export async function readSpec(specPath: string): Promise<RunnerSpec> {
  const absolutePath = resolvePath(specPath);
  const raw = await fs.readFile(absolutePath, "utf-8");
  return JSON.parse(raw) as RunnerSpec;
}

export function resolvePath(target: string): string {
  return path.isAbsolute(target) ? target : path.join(WORKFLOW_ROOT, target);
}

export async function ensureDir(targetDir: string): Promise<void> {
  await fs.mkdir(targetDir, { recursive: true });
}

export async function writeLog(component: string, task: string, payload: Record<string, unknown>) {
  const executionDir = path.join(LOGS_ROOT, "executions", component);
  await ensureDir(executionDir);
  const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
  const logPath = path.join(executionDir, `${task}-${timestamp}.json`);
  await fs.writeFile(logPath, JSON.stringify(payload, null, 2), "utf-8");
  return logPath;
}

export async function appendMetrics(row: string) {
  const metricsPath = path.join(LOGS_ROOT, "metrics.csv");
  await fs.appendFile(metricsPath, `\n${row}`);
}

export function formatDuration(start: number): number {
  return Date.now() - start;
}
